/*
 * @Author: xx
 * @Date: 2024-02-06 22:32:43
 * @LastEditors: Zhanghan
 * @LastEditTime: 2024-02-08 19:39:23
 * @Description: 
 */
import Taro from '@tarojs/taro';

// 错误定义
const HTTP_STATUS = {
    SUCCESS: 200,
    CREATED: 201,
    ACCEPTED: 202,
    CLIENT_ERROR: 400,
    AUTHENTICATE: 401,
    FORBIDDEN: 403,
    NOT_FOUND: 404,
    SERVER_ERROR: 500,
    BAD_GATEWAY: 502,
    SERVICE_UNAVAILABLE: 503,
    GATEWAY_TIMEOUT: 504
  }

const baseUrl='https://api.it120.cc/xiaochengxu/';

const interceptor = (chain) => {
    const requestParams = chain.requestParams
    return chain.proceed(requestParams).then(res => 
      {
        if(res.statusCode === HTTP_STATUS.NOT_FOUND){
          return Promise.reject("请求资源不存在")
        }else if(res.statusCode === HTTP_STATUS.BAD_GATEWAY){
          return Promise.reject("服务端出现问题")
        }else if(res.statusCode === HTTP_STATUS.FORBIDDEN){
          return Promise.reject("无权访问")
        }else if(res.statusCode === HTTP_STATUS.AUTHENTICATE){
          return Promise.reject("需要鉴权")
        }else{
          return res.data
        }
      }
    )
  }
  
  // 添加拦截器
  Taro.addInterceptor(interceptor);

  const baseHttp = ({
    url,
    data = {},
    method = "get",
    header = {},
    needToken=false,
  })=>{

    const handleHeader = {
        'content-type': 'application/json',
        ...header
      }

      if(needToken){
        data={
          ...data,
          token: ''
        }
      }

    return new Promise<any>((resolve, reject) => {
        const options:any ={
            url: `${baseUrl}${url}`,
            data,
            method,
            header: handleHeader,
            timeout:9000
          }
          Taro.request({
            ...options,
            success(result){
              resolve(result.data);
            },
            fail(e){
              console.log('网络异常')
              reject(e)
            }
          });
    })
  }

  export default baseHttp